package yaty.lee.study.ehcache.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

public class CacheUtil {
    private static CacheManager cacheMgr = null;

    private static Ehcache getCache(String cacheName) {
        if (cacheMgr == null) {
            cacheMgr = CacheManager.create();
        }

        Ehcache cache = null;
        if (cacheMgr != null) {
            cache = cacheMgr.getEhcache(cacheName);
        }

        return cache;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> getListFromCache(String cacheName, String key) {
        List<T> all = new ArrayList<T>();

        Ehcache cache = getCache(cacheName);

        Element element = null;
        if (cache != null) {
            element = cache.get(key);
        }

        if (element != null) {
            all = (List<T>) element.getObjectValue();
        }

        return all;
    }
}
